package com.mc.mcgoweb.gateway;

import com.alibaba.fastjson.JSON;
import com.mc.common.base.BaseResponse;
import com.mc.service.BaseApiService;
import com.mc.service.invoke.ApiServiceMapping;
import com.mc.service.invoke.ApiServiceMappingInfo;

import java.lang.reflect.InvocationTargetException;

/***
 * @ClassName ApiServiceHandler
 * @Description todo
 * @Author CC
 * @Date: 2019/4/9 19:42
 * @Version 1.0
 */
public class ApiServiceHandler {
    public static BaseResponse handle(String method, String messageBody) {
        ApiServiceMappingInfo apiService = ApiServiceMapping.getApiService(method);
        Object request = JSON.parseObject(messageBody, apiService.getParamClass()[0]);
        Object object = apiService.getServiceInstance();
        BaseResponse result = null;
        try {
            String subClassName = apiService.getServiceInstance().getClass().getSuperclass().getCanonicalName();
            if (BaseApiService.class.getCanonicalName().equals(subClassName)) {
                BaseApiService serviceClazz = (BaseApiService) apiService.getServiceInstance();
                result = (BaseResponse) apiService.getMethod().invoke(serviceClazz, request);
            } else {
                result = (BaseResponse) apiService.getMethod().invoke(object, request);
            }

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return result;
    }
}
